package com.xinyu.service.impl;

import com.xinyu.config.FileStorageProperties;
import com.xinyu.domain.Post;
import com.xinyu.mapper.LabelMapper;
import com.xinyu.mapper.PostMapper;
import com.xinyu.mapper.SiteMapper;
import com.xinyu.mapper.UserMapper;
import com.xinyu.service.IPostService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinyu.vo.BaseResult;
import com.xinyu.vo.PostRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author: XinYu
 * @since 2025-02-17
 */
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements IPostService {

    @Autowired
    private PostMapper postMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SiteMapper siteMapper;
    @Autowired
    private LabelMapper labelMapper;

    @Autowired
    private FileStorageProperties fileStorageProperties; // 注入配置类

    @Override
    public BaseResult queryByCondition(PostRequest postRequest) {
        List<Post> list = postMapper.queryByCondition(postRequest);
        for (Post post:list){
            post.setViewCount(post.getViewCount()+1);
            postMapper.updateById(post);
            if (StringUtils.isNotBlank(post.getUser().getHead()))
                if (!post.getUser().getHead().contains(fileStorageProperties.getBaseUrl()))
                    post.getUser().setHead(fileStorageProperties.getBaseUrl() + post.getUser().getHead());
        }
        Integer postCounts = postMapper.postCounts(postRequest);
        return BaseResult.ok(list,postCounts);
    }

    @Override
    public Post queryById(Integer id) {
        Post post = postMapper.selectById(id);
        post.setUser(userMapper.selectById(post.getUserId()));
        post.setSite(siteMapper.selectById(post.getSiteId()));
        post.setLabel(labelMapper.selectById(post.getLabelId()));

        post.setViewCount(post.getViewCount()+1);
        postMapper.updateById(post);
        if (StringUtils.isNotBlank(post.getUser().getHead()))
            post.getUser().setHead(fileStorageProperties.getBaseUrl() + post.getUser().getHead());
        return post;
    }
}
